﻿//Description:派工信息集成
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:Wangjh
//create Date:2018-04-18
//Rewriter:
//Rewrite Date:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using UFC.DBUtility;
using UFC.Common ;
using System.Data.OracleClient;
using System.Configuration;
using System.Xml;

namespace SendToWCAPPDispatchInfo
{
    class SendDispatchInfo
    {
        private const string m_RecordType = "SendDispatchInfo";
       
        /// <summary>
        /// 结转数据到派工中间表
        /// </summary>
        public void RunDispatchTableSync()
        {



            //System.Threading.Thread thInsertDispatch = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            //{
            //    try
            //    {
            //        InsertTableSendDispatch();//插入批次派工信息
            //    }
            //    catch (Exception e)
            //    {
            //        LogHelp.WriteError("插入批次派工信息", e);
            //    }
            //}));
            //thInsertDispatch.Start();

            //System.Threading.Thread thUpdateDispatchOfModify = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            //{
            //    try
            //    {
            //        UpdateDispatchOfModify();//更新派工修改结转信息
            //    }
            //    catch (Exception e)
            //    {
            //        LogHelp.WriteError("更新派工修改结转信息", e);
            //    }
            //}));
            //thUpdateDispatchOfModify.Start();

            //System.Threading.Thread thUpdateDispatchOfDelete = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            //{
            //    try
            //    {
            //        UpdateDispatchOfDelete();//更新派工删除结转信息
            //    }
            //    catch (Exception e)
            //    {
            //        LogHelp.WriteError("更新派工删除结转信息", e);
            //    }
            //}));
            //thUpdateDispatchOfDelete.Start();

            //do
            //{
            //    System.Threading.Thread.Sleep(100);
            //} while (thInsertDispatch.ThreadState != System.Threading.ThreadState.Stopped);//线程是否完成,插入批次派工信息
            //do
            //{
            //    System.Threading.Thread.Sleep(100);
            //} while (thUpdateDispatchOfModify.ThreadState != System.Threading.ThreadState.Stopped);//线程是否完成,更新派工修改结转信息
            //do
            //{
            //    System.Threading.Thread.Sleep(100);
            //} while (thUpdateDispatchOfDelete.ThreadState != System.Threading.ThreadState.Stopped);//线程是否完成,更新派工删除结转信息
        }
        /// <summary>
        /// 推送派工信息到WCAPP
        /// </summary>
        public void RunSendDispatchSync() {
            DataTable dt = GetWaitDispatchInfo();
            if (dt.Rows.Count == 0)
            {
                LogHelp.WriteLog("没有可处理的派工信息记录");
                return; 
            }
            foreach (DataRow dr in dt.Rows )
            {
                LogHelp.WriteLog("处理派工记录开始" + dr["taskNo"]);
                Dictionary<string, string> strList = new Dictionary<string, string>();
                strList.Add("TASKNO", dr["TASKNO"].ToString());//任务(派工)ID
                string strMsg = "";
                string type = "";
                if (dr["status"].ToString () == "0")//派工添加
                {
                    type = "派工添加";
                    AddDctionary(ref strList ,dr);
                    string strXml = CreateXML(strList,0);
                    LogHelp.WriteLog("推送的XML:"+strXml );
                    //ERPService.ErpAndAppSyncData mm = new ERPService.ErpAndAppSyncData();
                    //mm.ReqMsg = strXML;
                    //ERPService.ErpAndAppSyncDataResponse result = sap.ErpAndAppSyncData(mm);
                    //if (result != null)
                    //{
                    // strMsg = result.RespMsg;
                    //}
                }
                else if (dr["status"].ToString() == "1")//派工删除
                {
                    type = "派工删除";
                    string strXml = CreateXML(strList,1);
                    LogHelp.WriteLog("推送的XML:" + strXml);
                    //ERPService.ErpAndAppSyncData mm = new ERPService.ErpAndAppSyncData();
                    //mm.ReqMsg = strXML;
                    //ERPService.ErpAndAppSyncDataResponse result = sap.ErpAndAppSyncData(mm);
                    //if (result != null)
                    //{
                    // strMsg = result.RespMsg;
                    //}
                }
                else if (dr["status"].ToString() == "2")//派工修改
                {
                    type = "派工修改";
                    AddDctionary(ref strList, dr);
                    string strXml = CreateXML(strList,2);
                    LogHelp.WriteLog("推送的XML:" + strXml);
                    //ERPService.ErpAndAppSyncData mm = new ERPService.ErpAndAppSyncData();
                    //mm.ReqMsg = strXML;
                    //ERPService.ErpAndAppSyncDataResponse result = sap.ErpAndAppSyncData(mm);
                    //if (result != null)
                    //{
                    // strMsg = result.RespMsg;
                    //}
                }
                LogHelp.WriteLog("返回的XML:" + strMsg);
                //if (GetRcvXML(strMsg))
                //{
                //    UpdateDispatchTable(dr["taskno"].ToString());
                //    OracleDAL.InsertSyncRecord(dr["taskno"].ToString(), m_RecordType, type+"成功", 0);
                //}
                //else
                //{
                //    OracleDAL.InsertSyncRecord(dr["taskno"].ToString(), m_RecordType, strMsg, 0);
                //}
            }
        
        }

        #region 派工添加（结转数据）
        /// <summary>
        /// 获取结转表没有的派工记录
        /// </summary>
        /// <returns></returns>
        DataTable GetDispatchInfo() 
        {
            string strSql = @"
                            SELECT csd.containerstepdispatchid taskNo,pb.productname partNo,p.description PRODUCTDESCRIPTION,p.productrevision,
                            c.containername batchNo,LPAD (s.specno,4,'0') seqNo ,csd.qty COUNT,ut.attributevalue facCode,rd.resourcename weldNo,
                            e.employeename welderNo,to_char( csd.plannedstartdate,'yyyy/mm/dd hh24:mi:ss') startTime,to_char(csd.plannedfinishdate,'yyyy/mm/dd hh24:mi:ss') endTime,ws.workflowstepname stepname  FROM containerstepdispatch csd
                            LEFT JOIN container c ON c.containerid=csd.containerid
                            LEFT JOIN product p ON p.productid=c.productid
                            LEFT JOIN productbase pb ON pb.productbaseid=p.productbaseid
                            LEFT JOIN workflowstep ws ON  ws.workflowstepid=csd.workflowstepid
                            LEFT JOIN specbase sb ON sb.specbaseid=ws.specbaseid
                            LEFT JOIN spec s ON s.specid=NVL(sb.revofrcdid,ws.specid)
                            LEFT JOIN Userattribute ut ON ut.parentid=csd.factoryid AND ut.userattributename='分厂代码'
                            LEFT JOIN resourcedef rd ON rd.resourceid=csd.resourceid
                            LEFT JOIN EMPLOYEE E ON E.EMPLOYEEID=csd.WORKERID--工人 
                            LEFT JOIN mes_senddispatch_table mst ON mst.taskno=csd.containerstepdispatchid
                            WHERE csd.isuse=0 AND mst.taskno IS NULL
                            ";
            string dateNode  = ConfigurationManager.AppSettings["DateNode"];
            strSql +=string.Format (" AND CSD.createdate>=TO_DATE('{0}','yyyy/mm/dd hh24:mi:ss')",dateNode );
            return OracleHelper .Query_ReturnDatTable (strSql );
        }
        /// <summary>
        /// 插入到中间结转表
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        Boolean InsertTableSendDispatchOfRow(DataRow dr)
        {
            string insertSql = @"
                                INSERT INTO MES_SENDDISPATCH_TABLE T (T.TASKNO,T.PARTNO,T.PRODUCTDESCRIPTION,T.PRODUCTREVISION,T.BATCHNO,T.SEQNO,
                                T.STEPNAME,T.COUNT,T.FACCODE,T.WELDNO,T.WELDERNO,T.STARTTIME,t.endtime,Status,t.isintegration) VALUES(:TASKNO,:PARTNO,:PRODUCTDESCRIPTION,
                                :PRODUCTREVISION,:BATCHNO,:SEQNO,:STEPNAME,:COUNT,:FACCODE,:WELDNO,:WELDERNO,TO_DATE(:STARTTIME,'yyyy/mm/dd hh24:mi:ss'),TO_DATE(:endtime,'yyyy/mm/dd hh24:mi:ss'),0,1)
                                ";
            OracleParameter[] insertPara = new OracleParameter[13];
            insertPara[0] = OracleHelper.NewParameter(":TASKNO", dr["TASKNO"], OracleType.VarChar);
            insertPara[1] = OracleHelper.NewParameter(":PARTNO", dr["PARTNO"], OracleType.VarChar);
            insertPara[2] = OracleHelper.NewParameter(":PRODUCTDESCRIPTION", dr["PRODUCTDESCRIPTION"], OracleType.VarChar);
            insertPara[3] = OracleHelper.NewParameter(":PRODUCTREVISION", dr["PRODUCTREVISION"], OracleType.VarChar);
            insertPara[4] = OracleHelper.NewParameter(":BATCHNO", dr["BATCHNO"], OracleType.VarChar);
            insertPara[5] = OracleHelper.NewParameter(":SEQNO", dr["SEQNO"], OracleType.VarChar);
            insertPara[6] = OracleHelper.NewParameter(":STEPNAME", dr["STEPNAME"], OracleType.VarChar);
            insertPara[7] = OracleHelper.NewParameter(":COUNT", dr["COUNT"], OracleType.Number );
            insertPara[8] = OracleHelper.NewParameter(":FACCODE", dr["FACCODE"], OracleType.VarChar);
            insertPara[9] = OracleHelper.NewParameter(":WELDNO", dr["WELDNO"].ToString (), OracleType.VarChar);
            insertPara[10] = OracleHelper.NewParameter(":WELDERNO", dr["WELDERNO"], OracleType.VarChar);
            insertPara[11] = OracleHelper.NewParameter(":STARTTIME", dr["STARTTIME"] , OracleType.VarChar);
            insertPara[12] = OracleHelper.NewParameter(":endtime", dr["endtime"], OracleType.VarChar);
            int i = OracleHelper.ExecuteSql(insertSql, insertPara);
            if (i > 0)
                return true;
            else
                return false;
        }
        /// <summary>
        /// 插入派工信息到数据结转表
        /// </summary>
        void InsertTableSendDispatch()
        {
            DataTable dt = GetDispatchInfo();
            if (dt.Rows.Count  == 0)
                return;
            foreach (DataRow row in dt.Rows)
            {
                InsertTableSendDispatchOfRow(row);
            }
        }
        #endregion

        #region 派工修改（结转数据）
        /// <summary>
        /// 获取结转表中存在并派工修改的记录
        /// </summary>
        /// <returns></returns>
        DataTable GetDispatchOfUpdate() {
            string strSql = @"
                            SELECT csd.containerstepdispatchid taskNo,csd.qty COUNT,rd.resourcename weldNo,e.employeename welderNo,to_char( csd.plannedstartdate,'yyyy/mm/dd hh24:mi:ss') startTime,to_char(csd.plannedfinishdate,'yyyy/mm/dd hh24:mi:ss') endTime FROM containerstepdispatch csd
                            LEFT JOIN resourcedef rd ON rd.resourceid=csd.resourceid
                            LEFT JOIN EMPLOYEE E ON E.EMPLOYEEID=csd.WORKERID--工人 
                            LEFT JOIN mes_senddispatch_table mst ON mst.taskno=csd.containerstepdispatchid
                            WHERE csd.isuse =0 AND mst.taskno IS NOT NULL AND (
                            e.employeename<>mst.welderno OR rd.resourcename<>mst.weldno OR csd.qty<>mst.count OR mst.starttime<>csd.plannedstartdate OR mst.endtime<>csd.plannedfinishdate
                            )
                            ";
            return OracleHelper.Query_ReturnDatTable(strSql);
        }
         /// <summary>
        /// 派工修改更新
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        Boolean UpdateDispatchOfRow(DataRow dr ) {
            string strSql = @"
                            UPDATE mes_senddispatch_table t SET t.count=:count,t.welderno=:welderno,t.weldno=:weldno,t.starttime=TO_DATE(:STARTTIME,'yyyy/mm/dd hh24:mi:ss'),t.endtime=TO_DATE(:endtime,'yyyy/mm/dd hh24:mi:ss'),t.isintegration=1,t.status=2
                            WHERE t.taskno=:taskno
                            ";
            OracleParameter[] insertPara = new OracleParameter[6];
            insertPara[0] = OracleHelper.NewParameter(":count", dr["count"], OracleType.Number );
            insertPara[1] = OracleHelper.NewParameter(":welderno", dr["welderno"], OracleType.VarChar);
            insertPara[2] = OracleHelper.NewParameter(":weldno", dr["weldno"], OracleType.VarChar);
            insertPara[3] = OracleHelper.NewParameter(":starttime", dr["starttime"], OracleType.DateTime );
            insertPara[4] = OracleHelper.NewParameter(":endtime", dr["endtime"], OracleType.VarChar );
            insertPara[5] = OracleHelper.NewParameter(":taskno", dr["taskno"], OracleType.VarChar );
            int i = OracleHelper.ExecuteSql(strSql, insertPara);
            if (i > 0)
                return true;
            else
                return false;
        }
        void UpdateDispatchOfModify() {
            DataTable dt = GetDispatchOfUpdate();
            if (dt.Rows.Count == 0)
                return;
            foreach (DataRow row in dt.Rows)
            {
                UpdateDispatchOfRow(row);
            }
        }
        #endregion

        #region 派工删除（结转数据）
        /// <summary>
        /// 获取结转表有但已经删除的派工记录
        /// </summary>
        DataTable  GetdispatchOfDelete()
        {
            string strSql =@"SELECT  mst.* FROM mes_senddispatch_table mst
                            LEFT JOIN containerstepdispatch csd ON csd.containerstepdispatchid=mst.taskno
                            WHERE csd.containerstepdispatchid IS NULL AND mst.taskno IS NOT NULL";

            return OracleHelper .Query_ReturnDatTable (strSql );
        }
        /// <summary>
        /// 派工删除更新
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        Boolean ModifyDispatchOfRow(DataRow dr,int status) {
            string updateSql = @"UPDATE mes_senddispatch_table t SET t.isintegration=1 ,t.status=:status WHERE t.taskno=:taskno";
            OracleParameter[] updatePara = new OracleParameter[2];
            updatePara[0] = OracleHelper.NewParameter(":taskno", dr["taskno"], OracleType.VarChar);
             updatePara[1] = OracleHelper.NewParameter(":status", status, OracleType.Number );
            int i = OracleHelper.ExecuteSql(updateSql, updatePara);
            if (i > 0)
                return true;
            else
                return false;
        }
        /// <summary>
        /// 派工删除后更新结转表
        /// </summary>
        void UpdateDispatchOfDelete() {
            DataTable dt = GetdispatchOfDelete();
            if (dt.Rows.Count == 0)
                return;
            foreach (DataRow row in dt.Rows)
            {
                ModifyDispatchOfRow(row,1);
            }
        }
        #endregion

        /// <summary>
        /// 获取待推送的派工记录
        /// </summary>
        /// <returns></returns>
        DataTable GetWaitDispatchInfo() {
            string strSql = @"SELECT * FROM mes_senddispatch_table t WHERE t.isintegration=1";
            return OracleHelper.Query_ReturnDatTable(strSql);   
        }

        /// <summary>
        /// 给字典赋值
        /// </summary>
        /// <param name="strList"></param>
        /// <param name="dr"></param>
        void AddDctionary(ref Dictionary<string, string> strList,DataRow dr) 
        {
            strList.Add("PARTNO", dr["PARTNO"].ToString());//零件编号（图号）
            strList.Add("batchNo", dr["batchNo"].ToString());//批次号（零件图号/批次序号）
            strList.Add("seqNo", dr["seqNo"].ToString());//工序号（4位，不够前面补0）
            strList.Add("count", dr["count"].ToString());//派工数量
            strList.Add("facCode", dr["facCode"].ToString());//分厂代码（MES从PDM里面接收）
            strList.Add("weldNo", dr["weldNo"].ToString());//设备编号
            strList.Add("welderNo", dr["welderNo"].ToString());//员工编号（8位）
            strList.Add("startTime", dr["startTime"].ToString());//计划起始时间
            strList.Add("endTime", dr["endTime"].ToString());//计划终止时间
        }

        /// <summary>
        /// 创建xml字符串
        /// </summary>
        /// <param name="strList"></param>
        /// <returns></returns>
        private string CreateXML(Dictionary<string, string> strList,int type)
        {

            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode ReqNode = doc.CreateElement("ReqMsg");
            XmlNode headerNode = doc.CreateElement("header");
            XmlNode senderNode = doc.CreateElement("sendSysName");
            senderNode.InnerText = "APP_MES";
            XmlNode rcvNode = doc.CreateElement("rcvSysName");
            rcvNode.InnerText = "APP_ERP";
            XmlNode extNode = doc.CreateElement("extConfig");
            extNode.AppendChild(doc.CreateElement("isReTry"));
            extNode.LastChild.InnerText = "false";
            extNode.AppendChild(doc.CreateElement("FunName"));
            if (type == 0) //添加
            {
                extNode.LastChild.InnerText = "AddTask";
            }
            else if (type == 1)//删除
            {
                extNode.LastChild.InnerText = "DeleteTask";
            }
            else if (type == 2)//修改
            {
                extNode.LastChild.InnerText = "UpdateTask";
            }
           
            headerNode.AppendChild(senderNode);
            headerNode.AppendChild(rcvNode);
            headerNode.AppendChild(extNode);
            ReqNode.AppendChild(headerNode);
            XmlNode documentNode = doc.CreateElement("document");
            string strData = "<ALCNRINFO>";
            foreach (KeyValuePair<string, string> _key in strList)
            {
                strData = string.Format("{0}<{1}>{2}</{1}>", strData, _key.Key, _key.Value);
            }
            strData += "</ALCNRINFO>";
            documentNode.AppendChild(doc.CreateCDataSection(strData));
            ReqNode.AppendChild(documentNode);
            doc.AppendChild(ReqNode);
            return doc.InnerXml;
        }

        /// <summary>
        /// 获取ERP反馈XML
        /// </summary>
        /// <param name="strXML"></param>
        /// <returns></returns>
        private bool GetRcvXML(string strXML)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(strXML);
            string isSuccess = doc.SelectSingleNode("RespMsg/header/isSuccess").InnerText;
            string meaasge = doc.SelectSingleNode("RespMsg/header/message").InnerText;

            if (isSuccess == "true" || meaasge == "S")
                return true;
            else
            {
                LogHelp.WriteLog(meaasge);
                return false;
            }
        }

        /// <summary>
        /// 更新报废单信息转接标记
        /// </summary>
        /// <param name="ContainerStepScrapInfoID"></param>
        /// <param name="IsIntegration"></param>
        /// <returns></returns>
        private bool UpdateDispatchTable(string ContainerStepScrapInfoID)
        {
            string strSql = @"UPDATE mes_senddispatch_table SET ISINTEGRATION = 0";

            strSql += " WHERE taskno = :v_recordid";
            OracleParameter[] insertParam = new OracleParameter[1];

            insertParam[0] = new OracleParameter();
            insertParam[0].ParameterName = ":v_recordid";
            insertParam[0].OracleType = OracleType.VarChar;
            insertParam[0].Direction = ParameterDirection.Input;
            insertParam[0].Value = ContainerStepScrapInfoID;

            int i = OracleHelper.ExecuteSql(strSql, insertParam);
            if (i > 0)
                return true;
            else
                return false;
        }
    }
}
